<template>
  <el-form ref="form" :rules="loginRules" :model="form">
    <el-col :span="24">
      <el-form-item prop="userName">
        <el-input
          v-model="form.userName"
          placeholder="请输入用户名或手机号"
        ></el-input>
      </el-form-item>
    </el-col>
    <el-col :span="24">
      <el-form-item prop="password">
        <el-input
          v-model="form.password"
          placeholder="请输入密码"
          @keyup.enter.native="handleSubmit"
          class="passwordInput"
          ref="passwordInput"
          :maxlength="20"
          @input="handleInput"
          :type="inputType"
        >
          <template #append>
            <div @click="togglePassword" class="password-toggle">
              <img
                :src="passwordShow ? eyeOpenImg : eyeCloseImg"
                alt="切换密码显示"
                class="password-toggle-img"
              />
            </div>
          </template>
        </el-input>
      </el-form-item>
    </el-col>
    <el-col :span="24">
      <el-form-item prop="smsCode" v-if="isExpired">
        <el-input
          v-model="form.smsCode"
          prefix="ios-lock"
          size="large"
          clearable
          placeholder="请输入手机验证码"
          class="input-verify"
          autocomplete="off"
        >
          <template slot="append">
            <div class="sendCode">
              <el-button
                v-if="!countdown"
                class="get-msg"
                type="primary"
                @click="sendMsgByu"
                :disabled="!form.userName"
                >获取验证码</el-button
              >
              <el-button
                v-else
                class="get-msg"
                type="primary"
                :loading="countdown > 0"
                >{{ countdown + "s" }}</el-button
              >
            </div>
          </template></el-input
        >
      </el-form-item>
    </el-col>
    <el-col :span="9"> </el-col>
    <el-col :span="24">
      <span v-if="isExpired" class="isExpired"
        >由于您更换设备或长时间未登录，为了确保您的账号安全，请输入绑定手机验证码</span
      >
    </el-col>
    <el-col :span="15">
      <el-form-item prop="code">
        <el-input
          v-model.trim="form.code"
          placeholder="请输入图形码"
          @keyup.enter.native="handleSubmit"
          :maxlength="6"
        />
      </el-form-item>
    </el-col>
    <el-col :span="9">
      <div class="code">
        <img :src="imgPicture" alt="" @click="getPicture" />
      </div>
    </el-col>
    <el-col :span="24">
      <el-form-item>
        <div class="bottombuttons">
          <el-button type="primary" @click="handleSubmit" :loading="loading">
            登录
          </el-button>
          <div class="changeFormButtons">
            <!-- <p @click="changeForm('forget')" class="changeForm">
              忘记密码
            </p> -->
          </div>
        </div>
      </el-form-item>
    </el-col>
  </el-form>
</template>

<script>
import {
  SaaSUserLogin,
  expiredLogin,
  SaaSUserInfo,
  SaaSInitCaptcha,
  drawCodeImage,
  reqIsExpired,
  sendMsgByu,
} from "@/api/SaaS";
import { encrypt } from "@/utils/sm4.js";
import { burryPointForLogin } from "@/api/data";
export default {
  name: "SaaSloginForm",
  data() {
    return {
      countdown: 0,
      timer: null,
      isExpired: false,
      eyeOpenImg: "//img3.job1001.com/data_center/images/eyeOpen.png",
      eyeCloseImg: "//img3.job1001.com/data_center/images/eyeClose.png",
      codeInfoText: "发送验证码",
      disabledCatpchaFlash: false,
      captchaId: "",
      imgPicture: "",
      form: {
        userName: "",
        password: "",
        code: "",
        smsCode: "",
      },
      loginRules: {
        userName: [
          {
            required: true,
            trigger: "blur",
            message: "请输入用户名或手机号",
          },
        ],
        password: [{ required: true, trigger: "blur", message: "请输入密码" }],
        code: [
          { required: true, trigger: "blur", message: "请输入图形验证码" },
        ],
      },
      loading: false,
      passwordShow: false,
    };
  },
  computed: {
    inputType() {
      return this.passwordShow ? "text" : "password"; // 使用计算属性来动态返回类型
    },
  },
  created() {
    document.title = "登录";
    this.reqIsExpired();
    this.initCaptcha();
  },
  methods: {
    reqReportLoginAction() {
      const params = {
        rightId: "-2",
        cardType: localStorage.getItem("cardType"),
        description: "使用了职业大全",
        patform: 2,
        personId: "-1",
      };
      burryPointForLogin(params)
        .then((res) => {
          if (res.code == 200) {
          }
        })
        .catch((e) => {
          console.log(e);
        });
    },
    togglePassword() {
      this.passwordShow = !this.passwordShow;
      // 切换输入框类型
      this.$refs.passwordInput.type = this.passwordShow ? "text" : "password";
    },
    handleInput(value) {
      // 正则表达式：只允许英文字母、数字和特殊字符
      const validChars = value.replace(/[^a-zA-Z0-9._~!@#$^&*()\-+=]/g, "");

      // 将过滤后的内容更新到 password 中
      this.form.password = validChars;
    },
    handleSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          //通过验证
          this.loading = true;
          const params = {
            username: this.form.userName,
            password: encrypt(this.form.password),
            captcha: this.form.code,
            deviceId: this.captchaId,
          };
          let reqMethod = SaaSUserLogin;
          if (this.isExpired) {
            reqMethod = expiredLogin;
            params.smsCode = this.form.smsCode;
            params.passWord = encrypt(this.form.password);
            delete params.password;
            params.userName = params.username;
            delete params.username;
          }
          reqMethod(params)
            .then((res) => {
              if (res.code == 200) {
                // 登录成功处理
                this.$message.success("登录成功！");
                // token不同！！
                localStorage.setItem("token", res.data.cucToken);
                localStorage.setItem("SaaStoken", res.data.token);
                // 别删除，职途管理后台会用到
                localStorage.setItem("authorization", res.data.token);
                //存储用户身份,10代表学生,20代表教师
                localStorage.setItem("roleType", 20);
                this.reqReportLoginAction();
                this.$bus.$emit("generalReportAction", {
                  etId: 40000,
                  personId: "-1",
                  cardType: localStorage.getItem("cardType"),
                  jumpSource: 60,
                  sourceType: 60,
                });
                this.afterLogin(res);
              } else {
                this.$message.error(res.status_desc || "请重试！");
                this.getPicture();
              }
            })
            .catch((e) => {
              this.$message.error(e.response?.data?.status_desc || "请重试！");
              this.getPicture();
              console.log(e);
            })
            .finally(() => {
              this.loading = false;
            });
        } else {
          //console.log("error submit");

          return false;
        }
      });
    },
    changeForm(type) {
      this.$store.dispatch("user/setSaaSFormType", type);
    },
    //初始化并获取验证码
    async initCaptcha() {
      const res = await SaaSInitCaptcha();
      if (res.code == 200) {
        this.captchaId = res.data;
        let url = drawCodeImage + this.captchaId;
        this.imgPicture = url + "?time=" + new Date().getTime();
      } else {
        this.$message({
          type: "error",
          message: res.status_desc,
        });
      }
    },
    // 判断用户登录是否在七日之内
    reqIsExpired() {
      reqIsExpired().then((res) => {
        if (res.code == 200) {
          this.isExpired = res.data;
        }
      });
    },
    sendMsgByu() {
      if (!this.form.userName) {
        return this.$message.error("请输入手机号");
      }
      sendMsgByu({ userName: this.form.userName }).then((res) => {
        if (res.code == 200) {
          this.$message.success(res.status_desc);
          this.countdown = 60;
          this.timer = setInterval(() => {
            this.countdown--;
            if (this.countdown <= 0) {
              clearInterval(this.timer);
              this.timer = null;
            }
          }, 1000);
        } else {
          this.$message.error(res.status_desc);
        }
      });
    },
    //Saas登录后
    async afterLogin(res) {
      // 获取用户信息
      SaaSUserInfo().then((res) => {
        if (res.code == 200) {
          localStorage.setItem("userInfo", JSON.stringify(res.data));

          // 存储手机号码
          localStorage.setItem("mobile", res.data.mobile);
          localStorage.setItem("origin", 'loginPage');
          const query = { ...this.$route.query, origin: "loginPage" } || {};
          setTimeout(() => {
            console.log("query", query);
            this.$router.push({ name: "position", query });
          }, 300);
        }
      });
    },
    getPicture() {
      //500毫秒内最多获取一次；
      if (this.disabledCatpchaFlash) return;
      this.initCaptcha();
      this.disabledCatpchaFlash = true;
      setTimeout(() => {
        this.disabledCatpchaFlash = false;
      }, 1000);
    },
    stopScrollFun(evt) {
      evt = evt || window.event;
      if (evt.preventDefault) {
        // Firefox
        evt.preventDefault();
        evt.stopPropagation();
      } else {
        // IE
        evt.cancelBubble = true;
        evt.returnValue = false;
      }
      return false;
    },
  },
};
</script>

<style lang="scss">
// 写在这里才生效？？？
/* 去掉 Chrome 浏览器的数字输入框箭头 */
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

/* 去掉 Firefox 浏览器的数字输入框箭头 */
input[type="number"] {
  -moz-appearance: textfield;
}
</style>

<style lang="scss" scoped>
.isExpired {
  display: block;
  font-size: 12px;
  color: #c0c4cc;
  margin-bottom: 12px;
}
.passwordInput {
  ::v-deep .el-input__inner {
    border-right: 0;
    border-radius: 3px 0px 0px 3px;
  }
  ::v-deep .el-input-group__append {
    border-radius: 2px;
    background: #f4f6fa;
    border: 1px solid #e3e8ef;
    border-left: 0;
    padding: 0;
    width: 42px;
  }
  ::v-deep .el-input-group__append,
  .el-input-group__prepend {
    padding: 0;
  }
  .password-toggle {
    display: flex;
    justify-content: center;
    align-items: center;
    cursor: pointer;
    .password-toggle-img {
      width: 18px;
      height: 18px;
    }
  }
}
.code {
  display: flex;
  align-items: center;
  z-index: 10;
  height: 40px;
  cursor: pointer;
  font-size: 0px;
  img {
    max-width: 100%;
    height: 40px;
  }
}
::v-deep .el-form-item__error {
  font-size: 12px;
  color: #e85e41;
  line-height: 16px;
  text-align: left;
  font-style: normal;
  padding-top: 0px;
  padding-left: 12px;
}
::v-deep .el-input-group__append {
  border-radius: 2px;
  background: #f4f6fa;
  border: 1px solid #e3e8ef;
  padding: 0;
}
.sendCode {
  display: flex;
  justify-content: center;
  width: 100px;
  button {
    color: #0b6eff !important;
    background-color: transparent !important;
    border: 0px !important;
  }
}
.bottombuttons {
  ::v-deep .el-button {
    width: 100%;
    height: 32px;
    padding-top: 7px;
    padding-bottom: 7px;
  }
  .changeFormButtons {
    display: flex;
    justify-content: center;
    .changeForm {
      text-align: center;
      cursor: pointer;
      font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB,
        Microsoft YaHei, Arial, sans-serif;
      font-size: 14px;
      color: #666666;
      line-height: 19px;
      font-style: normal;
      margin: 10px 0 0 0;
      padding: 0 10px;
    }
  }
}
::v-deep .el-form-item {
  margin-bottom: 20px;
}
::v-deep .el-input__inner {
  width: 100%;
  height: 40px;
  background: #f4f6fa;
  border-radius: 3px;
  border: 1px solid #e3e8ef;
}
::v-deep .el-form-item.is-error .el-input__inner {
  border-color: #e3e8ef;
}

/* 去掉 Chrome 浏览器的数字输入框箭头 */
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

/* 去掉 Firefox 浏览器的数字输入框箭头 */
input[type="number"] {
  -moz-appearance: textfield;
}
::v-deep.el-input .el-input__inner {
  line-height: 1px !important;
}

@media (max-width: 1440px) {
  .login-block {
    top: 120px !important;
  }
}
</style>
